﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FlexExplorer
{
	public partial class ListViewEx : ListView
	{
		public ListViewEx()
		{
			InitializeComponent();
		}

		const string DIRECTORY_IDENTIFIER = "<DIR>";
		const string GO_UPPER_IDENTIFIER = "<UP>";

		protected override void OnBeforeLabelEdit(LabelEditEventArgs e)
		{
			this.SelectedItems[0].Text = viewedLabel;
		}

		public void BeginEdit()
		{
			if (this.SelectedItems.Count != 1)
				return;

			StartLabelEdit();
		}

		private string editedLabel;
		private string viewedLabel;

		private void StartLabelEdit()
		{
			ListViewItem item = this.SelectedItems[0];
			viewedLabel = item.Text;

			if (item.SubItems[1].Text == GO_UPPER_IDENTIFIER)
				return;

			if (item.SubItems[1].Text != DIRECTORY_IDENTIFIER && item.SubItems[1].Text != String.Empty)
				item.Text += item.SubItems[1].Text;

			LabelEditEventArgs e = new LabelEditEventArgs(item.Index);
			base.OnBeforeLabelEdit(e);

			editedLabel = item.Text;
			this.LabelEdit = true;
			item.BeginEdit();
		}

		protected override void OnAfterLabelEdit(LabelEditEventArgs e)
		{
			if (e.Label == null)
				return;
			
			string extension = Path.GetExtension(e.Label);
			string filename = Path.GetFileNameWithoutExtension(e.Label);

			this.Items[e.Item].Text = filename;
			this.Items[e.Item].SubItems[1].Text = extension;

			this.LabelEdit = false;

			base.OnAfterLabelEdit(e);		
		}
	}
}
